'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-09-25 09:48:29
@LastEditTime: 2019-12-05 16:06:24
@LastEditors: Please set LastEditors
'''

from ...service.welfare_institution.accommodation_process import AccommodationProcess
import time
from ...service.mongo_bill_service import MongoBillFilter
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...pao_python.pao.service.security.security_service import RoleService
from enum import Enum
import hashlib
import re
import datetime
import uuid
import pandas as pd
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
# -*- coding: utf-8 -*-

'''
住宿记录函数
'''


class LeaveRecordState(Enum):
    '''请假状态类型枚举'''
    leave = '离开'
    check_in = '入住'


class LeaveRecordService(MongoService):
    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.accommodation_process = AccommodationProcess(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def update_leave_record(self, leaveRecord):
        '''编辑或新增住宿记录'''
        res = 'Fail'
        now_date = datetime.datetime.now()
        leaveRecord['apply_date'] = datetime.datetime.now()
        if 'id' in leaveRecord.keys():
            ''' 录入离开信息'''
            leaveRecord['checkout_date'] = now_date
            leaveRecord['status'] = LeaveRecordState.leave.value
            # 查询目前最新数据
            _filter = MongoBillFilter()
            _filter.match_bill(C('id') == leaveRecord['id'])
            old_leave_record = self.query(_filter, 'PT_Accommodation_Record')
            if len(old_leave_record) > 0:
                data_info = old_leave_record[0].copy()
                data_info.update(leaveRecord)
                data_info.pop("_id")
                # data_info.pop("invalid_bill_id")
                # print('111111111111111',data_info)
                res_data = self.accommodation_process.create_accommodation_data(
                    data_info)
                # print('22222222222222222',data_info)
                # 服务项目记录对象数组
                record_item_datas = res_data['record_item_datas']
                # 住宿记录对象
                accommodation_data = res_data['accommodation_data']
                # print('>>>>>>>>>>>>>>>>>>>>>',record_item_datas)
                bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                            TypeId.LeaveRecord.value, accommodation_data, 'PT_Accommodation_Record')
                record_bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                                   TypeId.LeaveRecord.value, [record_item_datas], 'PT_Service_Record')
                if bill_id and record_bill_id:
                    res = 'Success'
            else:
                return '找不到入住记录'

        else:
            ''' 录入入住信息'''
            leaveRecord['checkin_date'] = now_date
            leaveRecord['status'] = LeaveRecordState.check_in.value
            record_id = str(uuid.uuid1())
            leaveRecord['id'] = record_id
            # 更新入住记录表信息 check_in表
            _filter = MongoBillFilter()
            _filter.match_bill(
                (C('user_id') == leaveRecord['residents_id']) & (C('state') == '居住中'))
            check_in_org = self.query(_filter, 'IEC_Check_In')
            if len(check_in_org) > 0:
                check_in_data = check_in_org[0]
                check_in_data['accommodation_id'] = record_id
                # if check_in_data.get('order_id'):
                #     _filter_order = MongoBillFilter()
                #     _filter_order.match_bill(C('id') == check_in_data.get('order_id')).project({'_id':0})
                #     res_order = self.query(_filter_order,'PT_Service_Order')
                #     if res_order:
                #         res_order[0]['status'] = '未服务'
                #         res_order[0]['id'] = str(uuid.uuid1())

                # print(leaveRecord, 'leaveRecord>>')
                leave_bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                                  TypeId.LeaveRecord.value, leaveRecord, 'PT_Accommodation_Record')
                bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                            TypeId.LeaveRecord.value, check_in_data, 'IEC_Check_In')
                if leave_bill_id and bill_id:
                    res = 'Success'
        return res
        # if not LeaveRecord.get('status'):
        #     LeaveRecord['status'] = LeaveRecordState.Status.value
        #     _filter = MongoBillFilter()
        #     _filter.match_bill((C('residents_id') == LeaveRecord['residents_id']) & (C('status') == LeaveRecord['status']))\
        #         .project({'_id': 0})
        #     res1 = self.query(
        #         _filter, 'PT_Accommodation_Record')
        #     if len(res1) > 0:
        #         res = 'fail'
        #         return res
        #     else:
        #         if LeaveRecord.get('apply_date'):
        #             LeaveRecord['apply_date'] = as_date(
        #                 LeaveRecord.get('apply_date'))
        #         # if leaveInsert.get('checkin_date'):
        #             #leaveInsert['checkin_date'] = as_date(leaveInsert.get('checkin_date'),'%Y-%m-%dT%H:%M:%S.%fZ')
        #         if LeaveRecord.get('checkout_date'):
        #             LeaveRecord['checkout_date'] = as_date(
        #                 LeaveRecord.get('checkout_date'))

        #         def process_func(db):
        #             nonlocal res
        #             LeaveRecord['status'] = '离开'
        res_data = self.accommodation_process.create_accommodation_data(
            leaveRecord)
        # 服务项目记录对象数组
        record_item_datas = res_data['record_item_datas']
        bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                    TypeId.LeaveRecord.value, [res_data['accommodation_data'], record_item_datas], ['PT_Accommodation_Record', 'PT_Service_Record'])
        if bill_id:
            res = 'Success'
        #         process_db(self.db_addr, self.db_port,
        #                    self.db_name, process_func)
        #         return res
        # else:
        #     if LeaveRecord.get('apply_date'):
        #         LeaveRecord['apply_date'] = as_date(
        #             LeaveRecord.get('apply_date'))
        #     if LeaveRecord.get('checkin_date'):
        #         LeaveRecord['checkin_date'] = as_date(
        #             LeaveRecord.get('checkin_date'))
        #     if LeaveRecord.get('checkout_date'):
        #         LeaveRecord['checkout_date'] = as_date(
        #             LeaveRecord.get('checkout_date'))

        #     def process_func(db):
        #         nonlocal res
        #         if 'id' in LeaveRecord.keys():
        #             LeaveRecord['status'] = '入住'
        #             bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
        #                                                         TypeId.LeaveRecord.value, LeaveRecord, 'PT_Accommodation_Record')
        #             if bill_id:
        #                 res = 'Success'
        #     process_db(self.db_addr, self.db_port, self.db_name, process_func)
        #     return res

    def get_leave_record_list(self, condition, page, count):
        '''获取请假销假列表'''
        keys = ['id']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_User', 'residents_id', 'id', 'user')\
            .lookup_bill('PT_Bed', 'bed_id', 'id', 'bed')\
            .lookup_bill('PT_User', 'pickout_id', 'id', 'user')\
            .lookup_bill('PT_User', 'operating_personnel_id2', 'id', 'user')\
            .add_fields({'elder_name': '$user.name',
                         'bed_number': '$bed.bed_code',
                         'pickout_name': '$user.name',
                         'operating_name': '$user.name',
                         'elder_number': '$user.personnel_category',
                         'create_date': '$create_date',
                         'modify_date': '$modify_date'})\
            .match((C('bill_status') == Status.bill_valid.value) & (C('id') == values['id']))\
            .project({'_id': 0, 'user._id': 0, 'bed._id': 0})
        res = self.page_query(
            _filter, 'PT_Accommodation_Record', page, count)
        return res

    def get_leave_list(self, org_list, condition, page, count):
        '''获取请假列表'''
        keys = ['id', 'status', 'residents_id', 'bed_name']
        # condition['status'] = '离开'
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.inner_join_bill('PT_User', 'residents_id', 'id', 'user')\
               .inner_join_bill('PT_Bed', 'bed_id', 'id', 'bed')\
               .lookup_bill('PT_Leave_Reason', 'record_reason_id', 'id', 'reason')\
               .add_fields({'elder_name': '$user.name',
                            'reason_type': '$reason.name',
                            'elder_number': '$user.personnel_category',
                            'create_date': '$create_date',
                            'modify_date': '$modify_date'})\
               .match_bill((C('id') == values['id'])
                           & (C('status') == values['status'])
                           & (C('bed.name').like(values['bed_name']))
                           & (C('residents_id') == values['residents_id'])
                           & (C('organization_id').inner(org_list)))\
               .sort({'apply_date': -1})\
               .project({'_id': 0, 'user._id': 0, 'bed._id': 0, 'reason._id': 0})
        res = self.page_query(
            _filter, 'PT_Accommodation_Record', page, count)
        return res

    def del_leave_record(self, ids):
        '''删除住宿记录'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            for id in ids:
                data = find_data(db, 'PT_Accommodation_Record', {
                    'id': id, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    self.bill_manage_service.add_bill(OperationType.delete.value,
                                                      TypeId.accommodationRecord.value, data[0], 'PT_Accommodation_Record')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def get_leave_reason_list(self, org_list,  condition, page, count):
        '''获取离开原因列表'''
        keys = ['id', 'name', 'code']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('name').like(values['name'])) & (C('id') == values['id']))\
               .project({'_id': 0})
        res = self.page_query(
            _filter, 'PT_Leave_Reason', page, count)
        return res

    def update_leave_reason(self, leave_reason):
        '''编辑或新增离开原因'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            if 'id' in leave_reason.keys():
                bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                            TypeId.accommodationRecord.value, leave_reason, 'PT_Leave_Reason')
                if bill_id:
                    res = 'Success'
            else:
                bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                            TypeId.accommodationRecord.value, leave_reason, 'PT_Leave_Reason')
                if bill_id:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def del_leave_reason(self, ids):
        '''删除离开原因'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            for id in ids:
                data = find_data(db, 'PT_Leave_Reason', {
                    'id': id, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    self.bill_manage_service.add_bill(OperationType.delete.value,
                                                      TypeId.accommodationRecord.value, data[0], 'PT_Leave_Reason')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res
